package com.meteor.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.meteor.pojo.Blog;
import com.meteor.pojo.Type;
import com.meteor.service.BlogService;
import com.meteor.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class BlogController {

    @Resource
    private BlogService blogService;

    @Resource
    private TypeService typeService;

    @GetMapping
    public String go() {
        return "redirect:/1";
    }

    /**
     * 博客主页面实现分页
     */
    @GetMapping("/{pageNum}")
    public String index(@PathVariable int pageNum, String title, Model model) {
        PageHelper.startPage(pageNum,5);
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        queryWrapper.like(title != null,Blog::getTitle,title);
        queryWrapper.orderByDesc(Blog::getId);
        List<Blog> list = blogService.list(queryWrapper);
        List<Type> types = typeService.list();
        wrapper.select("sum(views) as views");
        Blog one = blogService.getOne(wrapper);
        PageInfo<Blog> pageInfo = new PageInfo<>(list);
        model.addAttribute("viewS",one.getViews());
        model.addAttribute("types",types);
        model.addAttribute("page",pageInfo);
        model.addAttribute("blogs",list);
        return "index";
    }

    /**
     * 根据标题进行全局搜索
     */
    @GetMapping("/selectBlogByTitle")
    @ResponseBody
    public List<Blog> byTitle(String title) {
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.like("title",title);
        return blogService.list(wrapper);
    }


    /**
     * 进入博客详情页面
     */
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        Blog blog = blogService.getAndConvert(id);
        blog.setViews(blog.getViews()+1);
        blogService.updateById(blog);
        model.addAttribute("blog",blog);
        return "blog";
    }
}
